<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- layout布局 -->

      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 搜索和添加区域 -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList()"
          >
            <el-button
              slot="append"
              @click="getUserList()"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域-->
      <el-table :data="userList" border stripe>
        <el-table-column label="id" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 这里是使用了具名插槽 -->
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180cm">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="eidtDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserInfo(scope.row.id)"
            ></el-button>
            <!-- 设置按钮 -->
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="allotRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域   -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 点击添加用户 显示对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogClosed()"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-addForm"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击修改 显示对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="eidtDialogClosed()"
    >
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input disabled v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eidtUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!--  点击分配角色 显示对话框-->
    <el-dialog
      title="分配角色"
      :visible.sync="allotRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleRight()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>



<script>
export default {
  data() {
    // 验证邮箱
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则
      const regEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (regEmail.test(value)) return callback();
      callback(new Error("请输入合法的邮箱号码"));
    };
    // 验证手机号码
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则
      const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (regMobile.test(value)) return callback();
      callback(new Error("请输入合法的手机号码"));
    };
    return {
      queryInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页要显示多少条
        pagesize: 2,
      },
      userList: [],
      total: 0,
      // 控制对话框是否显示
      dialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 用户验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入您的邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入您的手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // editDialogVisible 控制修改对话框是否显示
      editDialogVisible: false,
      // 查询到的用户信息对象
      userForm: {},
      // 点击用户列表中修改弹出对话框的验证规则
      userFormRules: {
        email: [
          { required: true, message: "请输入您的邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入您的手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 分配角色对话框显示或隐藏
      allotRoleDialogVisible: false,
      // 储存用户信息
      userInfo: "",
      // 所有角色的数据列表
      roleList:[],
      // 选中的角色
      selectedRoleId:''
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$Message.error("获取用户列表信息错误");
      // this.$Message.success("获取用户列表信息成功");
      this.userList = res.data.users;
      this.total = res.data.total;
      console.log(res);
    },
    // 几页每条监听
    handleSizeChange(newSize) {
      // console.log(newSize + "newsize");
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 当前页监听
    handleCurrentChange(newCurrent) {
      // console.log(newCurrent);
      this.queryInfo.pagenum = newCurrent;
      this.getUserList();
    },
    // 监听用户状态
    async userStateChanged(newState) {
      console.log(newState);
      const { data: res } = await this.$http.put(
        `users/${newState.id}}/state/${newState.mg_state}`
      );
      if (res.meta.status !== 200) {
        newState.mg_state = !newState.mg_state;
        this.$Message.error("更新用户状态失败");
      }
      this.$Message.success("更新用户状态成功");
    },
    // 监听对话框关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击确定按钮添加新用户
    addUserInfo() {
      this.$refs.addFormRef.validate(async (valid) => {
        //  valid 是个布尔值
        //  console.log(valid);
        if (!valid) return;

        //  如果预验证正确，发起网络请求
        const { data: res } = await this.$http.post("users", this.addForm);
        // console.log(res);

        // 发送网络请求成功
        if (res.meta.status !== 201) return this.$Message.error("添加用户失败");
        this.$Message.success("添加用户成功");
        this.dialogVisible = false;
        this.getUserList();
      });
    },
    // 点击修改按钮，展示对话框
    async eidtDialog(id) {
      // console.log(id);
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$Message.error("查询用户信息失败！");
      }
      this.userForm = res.data;
      this.editDialogVisible = true;
    },
    //监听关闭按钮  重置表格
    eidtDialogClosed() {
      this.$refs.userFormRef.resetFields();
    },
    // 修改用户信息并提交
    eidtUserInfo() {
      this.$refs.userFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        // 发送修改用户信息的请求
        const { data: res } = await this.$http.put(
          "users/" + this.userForm.id,
          { email: this.userForm.email, mobile: this.userForm.mobile }
        );
        // console.log(res);

        if (res.meta.status !== 200)
          return this.$Message.error("修改用户信息请求失败！");
        // 请求成功
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据
        this.getUserList();
        // 提示对话框
        this.$Message.success("修改用户信息请求成功！");
      });
    },
    //用户列表中点击删除按钮弹框
    async removeUserInfo(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(typeof confirmResult);
      if (confirmResult !== "confirm")
        // 取消删除
        return this.$Message.info("您取消了删除数据");

      // 发送删除请求
      console.log("确定删除");
      const { data: res } = await this.$http.delete("users/" + id);
      // console.log(ceshi);
      if (res.meta.status != 200)
        return this.$http.error("删除数据请求不成功！");
      // 更新数据
      this.getUserList();
      // 删除数据成功
      this.$http.success("删除用户成功!");
    },
    // 监听分配角色
   async allotRole(userInfo) {
      this.userInfo = userInfo;
      // console.log("222");
      // 在显示对话框之前获取角色列表
     const {data: res} =await this.$http.get('roles')
    if(res.meta.status!==200) {return this.$Message.error("获取角色列表失败")}
    this.$Message.success("获取角色列表成功")
    this.roleList = res.data
      this.allotRoleDialogVisible = true;
    },
    // 分配角色权限
    async setRoleRight(){
      // 先判断有没有对select进行选择
      if(!this.selectedRoleId) {return this.$Message.error("请分配角色")}

     const {data:res} =  await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId})
     console.log(res);
     if(res.meta.status!==200) {return this.$Message.error("分配角色失败!"+res.meta.msg) }
      this.$Message.success(res.meta.msg)
      this.getUserList();
      this.allotRoleDialogVisible = false;
    },
    // 关闭分配权限对话框
    setRoleDialogClosed(){
      this.selectedRoleId = ''
      this.userInfo= []
    }
  },
};
</script>

<style scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>